const jwt = require('jsonwebtoken');

module.exports = () => {
  return async function jwtAuth(ctx, next) {
    try {
      const token = ctx.request.header.authorization.split(' ')[1];
      const decoded = jwt.verify(token, ctx.app.config.jwt.secret);
      ctx.request.user = decoded;
      await next();
    } catch (err) {
      ctx.throw(401, err.message);
    }
  };
};